<template>
  <qx-table :dbRowClick="rowDblClick" :option="tableOption" :remoteData="remoteData">
    <template v-slot:top>
      <qx-form v-model="searchForm" :option="tableOption" isSearch @submit="startSearch"></qx-form>
    </template>
    <template v-slot:menuLeft>
      <q-btn outline text-color="primary" @click="handleSync('rcs', $t('Misc.SynchronizeRCSData'))">
        {{ $t('Misc.SynchronizeRCSData') }}
      </q-btn>
      <q-btn outline text-color="primary" @click="handleSync('toRcs', $t('Misc.SynchronizeToRCS'))">
        {{ $t('Misc.SynchronizeToRCS') }}
      </q-btn>
      <q-import :errorParam="['AGV_MAS_DATA', 'importAgvMasDataPositionManagement']"
                downUrl="/yfagv/api/agvMasDataPositionManagement/importInfoTemplate"
                importUrl="/yfagv/api/agvMasDataPositionManagement/importInfo" @import-after="startSearch"></q-import>
    </template>
    <template v-slot:menuLeftR>
      <q-icon color="warning" name="mdi-map-marker-question cursor-pointer cursor-hover" size="1.5rem">
        <q-tooltip class="q-pa-md" v-bind="$tooltipAttr">{{ $t('Misc.DblClickCardTips') }}</q-tooltip>
      </q-icon>
    </template>
    <template v-slot:menu="{ row }">
      <q-btn class="col" color="primary" icon="mdi-square-edit-outline" outline unelevated @click="handleUpdate(row)">
        {{ $t('Edit') }}
      </q-btn>
    </template>
  </qx-table>
  <q-modal v-model="modalVisible" :header="formInfo.id ? $t('Edit') : $t('Add')" :width="500" @beforeClose="beforeClose"
           @confirm="submitForm">
    <qx-form ref="FormRef" v-model="formInfo" :option="tableOption"></qx-form>
  </q-modal>
  <q-modal v-model="syncModelVisible" :header="header" width="400" @beforeClose="beforeClose" @confirm="submitSync">
    <qx-form ref="FormRef" v-model="formInfo" :option="syncOption"></qx-form>
  </q-modal>
  <q-modal v-model="infoVisible" :header="`${$t('Misc.SpecifyDetails')}`" :menuBtn="false" :persistent="false"
           width="620">
    <QInfo :columns="tableOption.column || []" :rowInfo="formInfo" cols="2" headerWidth="100"></QInfo>
  </q-modal>
</template>
<script setup>
import { i18n, toI18nName } from 'boot/i18n.js'
import { postAPI, putAPI } from 'src/api/index.js'
import { getRemoteData, setRemoteData } from 'src/enum/ajaxRemoteData.js'
import { enableOrDisable } from 'src/enum/index.js'
import { slotIdentifiers } from 'src/views/CarrierCore/enum.js'
import { computed, onMounted, ref } from 'vue'
import { createDialog, deepClone } from 'src/utils/utils.js'

const header = ref('')
const formInfo = ref({})
const FormRef = ref(null)
const AGVBrands = ref([])
const searchForm = ref({})
const infoVisible = ref(false)
const modalVisible = ref(false)
const syncModelVisible = ref(false)
const remoteData = ref({ dicUrl: '/yfagv/api/agvMasDataPositionManagement/list' })
getRemoteData('agv_brand', '/yfagv/api/agvCfgBrand/list').then(data => (AGVBrands.value = data))
const brandProps = computed(() => ({ label: `${toI18nName('agvBrandNameZhCn')}`, value: 'agvBrandCode' }))
const syncOption = computed(() => {
  return {
    span: 22, labelWidth: 90,
    column: [{
      label: `${i18n.t('AGVCore.AGVBrand')}`, field: 'agvBrandCode', type: 'select', options: AGVBrands.value,
      props: brandProps.value, required: true
    }]
  }
})
const tableOption = computed(() => {
  return {
    grid: true, span: 22, export: true, searchLabelWidth: 60, headerWidth: 60, searchSpan: 4, labelWidth: 100,
    column: [{
      label: `${i18n.t('CarrierCore.SlotCode')}`, field: 'positionNo', minWidth: 100, readonly: true
    }, {
      label: `${i18n.t('CarrierCore.GuestSlotCode')}`, field: 'warehouseNo', minWidth: 100, required: true
    }, {
      label: `${i18n.t('CarrierCore.RackCode')}`, field: 'shelfNo', minWidth: 100, readonly: true
    }, {
      label: `${i18n.t('CarrierCore.SlotType')}`, field: 'slotType', minWidth: 100, required: true,
      format: (_, row) => formatValue(row), search: false, display: false
    }, {
      label: `${i18n.t('CarrierCore.SlotIdentifier')}`, field: 'positionType', type: 'select',
      options: slotIdentifiers.value, minWidth: 100, readonly: true, useTag: true, topLeft: true, search: false
    }, {
      label: `${i18n.t('IsEnable')}`, field: 'isEnable', type: 'radio', searchType: 'select', value: '1',
      options: enableOrDisable.value, useTag: true, topRight: true, search: false, display: false
    }, {
      label: `${i18n.t('CreationTime')}`, field: 'createdTime', minWidth: 70,
      search: false, display: false
    }]
  }
})

const formatValue = row => {
  const msg = row.k === '1' ? i18n.t('Misc.DoubleDeepSlot') : i18n.t('Misc.NonDoubleDeepSlot')
  return `${row.positionDepth || 0}x${row.positionWidth || 0}x${row.positionHeight || 0}mm ${msg}`
}
const rowDblClick = row => {
  formInfo.value = row
  infoVisible.value = true
}
const handleUpdate = row => {
  formInfo.value = deepClone(row)
  modalVisible.value = true
}
const handleSync = (source, title) => {
  header.value = title
  formInfo.value = { source }
  const msg = source === 'rcs' ? `${i18n.t('Misc.SyncTip1')}` : `${i18n.t('Misc.SyncTip2')}`
  createDialog({ msg }, () => {
    syncModelVisible.value = true
  }, () => {})
}
const formatSearchForm = () => ({ ...searchForm.value })
const startSearch = (action, done) => {
  remoteData.value.params = formatSearchForm()
  remoteData.value.clearSelected = true
  if (done) done()
  action === 'clear' && setRemoteData('agv_slot')
}
const beforeClose = () => {
  if (FormRef.value) FormRef.value.onReset()
  modalVisible.value = false
  syncModelVisible.value = false
}
const submitForm = (mDone) => {
  FormRef.value.validate((form, done) => {
    const API = form.id ? putAPI : postAPI
    API('/yfagv/api/agvMasDataPositionManagement', form, () => {
      startSearch('clear')
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}
const submitSync = mDone => {
  FormRef.value.validate((form, done) => {
    const uri = form.source === 'rcs' ? '/yfagv/api/syncRcsToFactoryApi/syncAgvMasDataPositionManagement'
      : '/yfagv/api/syncRcsApi/syncAgvMasDataPosition'
    postAPI(uri, form, () => {
      form.source === 'rcs' && startSearch('clear')
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}

onMounted(startSearch)
</script>